/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
  let tag = 0;
  let result = [];

  const maxList = l1.length >= l2.length ? l1 : l2;
  const minList = l1.length >= l2.length ? l2 : l1;

  for (let i = maxList.length - 1; i >= 0; i--) {
    let _tag = maxList[i] + (minList[i] ? minList[i] : 0) + tag;
    if (_tag >= 10) {
      result.unshift(_tag % 10);
      tag = 1;
    } else {
      result.unshift(_tag);
      tag = 0;
    }
  }
  if (tag != 0) {
    result.unshift(1);
  }
  return result;
};

var g_addTwoNumbers = function (l1, l2) {
  let head = null,
    tail = null;

  let carry = 0;
  while (l1 || l2) {
    const n1 = l1 ? l1.val : 0;
    const n2 = l2 ? l2.val : 0;
    const sum = n1 + n2 + carry;
    if (!head) {
      head = tail = new ListNode(sum % 10);
    } else {
      tail.next = new ListNode(sum % 10);
      tail = tail.next;
    }
    carry = Math.floor(sum / 10);
    if (l1) {
      l1 = l1.next;
    }
    if (l2) {
      l2 = l2.next;
    }
  }
  if (carry > 0) {
    tail.next = new ListNode(carry);
  }
  return head;
};

console.log(g_addTwoNumbers([2, 4, 3], [5, 6, 4]));
